#include "func_record.h"
#include "common/framework/platform_init.h"
#include "kernel/os/os_time.h"
#include "audio/pcm/audio_pcm.h"
#include "audio/manager/audio_manager.h"
#include "common/apps/recorder_app.h"
#include "fs/fatfs/ff.h"
#include "common/framework/fs_ctrl.h"

#define SAVE_RECORD_DATA_DURATION_MS  (10*1000)
#define AUDIO_PATH_TEST  "record_test.pcm"

static OS_Thread_t  thread_record_t  = {OS_INVALID_HANDLE} ; 
static bool flag_recording = false ;

/**
 * @brief 每次打开声卡，都需要重新设置
 * 
 */
static void func_record_init(){
    audio_manager_handler(AUDIO_SND_CARD_DEFAULT, AUDIO_MANAGER_SET_ROUTE, AUDIO_IN_DEV_DMIC, 1);
    // dmic 不支持调节增益, 只能手动调节
    // audio_manager_handler(AUDIO_SND_CARD_DEFAULT, AUDIO_MANAGER_SET_VOLUME_GAIN , AUDIO_IN_DEV_DMIC, 10);
}

static void task_record_callback(void * param){
    int ret;
	FIL file;
	void *data;
	unsigned int len;
	unsigned int writeLen;
	struct pcm_config config;
	unsigned int tick;
	unsigned int startTime;
	unsigned int nowTime;

	f_open(&file, AUDIO_PATH_TEST, FA_CREATE_ALWAYS | FA_READ | FA_WRITE);

	config.channels = 2; // dmic只能是2通道
	config.format = PCM_FORMAT_S16_LE;
	config.period_count = 2;
	config.period_size = 1024;
	config.rate = 16000;
	
    printf("snd_pcm_open start \n");
    func_record_init();
	ret = snd_pcm_open(AUDIO_SND_CARD_DEFAULT, PCM_IN, &config);
	if (ret) {
		printf("snd_pcm_open fail.\n");
		goto err;
	}

	len = config.channels * config.period_count * config.period_size;
	data = malloc(len);
	if (data == NULL) {
		goto err1;
	}

	tick = OS_GetTicks();
	startTime = OS_TicksToMSecs(tick);

	printf("===start record pcm by audio driver, last for %dms===\n", SAVE_RECORD_DATA_DURATION_MS);
    flag_recording = true ;
	while ( flag_recording ) {
		ret = snd_pcm_read(AUDIO_SND_CARD_DEFAULT, data, len);
		if (ret != len) {
			printf("snd_pcm_read fail.\n");
		}

		f_write(&file, data, len, &writeLen);

        #if 0 
            tick = OS_GetTicks();
            nowTime = OS_TicksToMSecs(tick);
            if ((nowTime - startTime) > SAVE_RECORD_DATA_DURATION_MS) {
                break;
            }
        #endif ;
	}
	printf("record pcm over.\n");

	free(data);

err1:
	snd_pcm_close(AUDIO_SND_CARD_DEFAULT, PCM_IN);
err:
	f_close(&file);

    OS_ThreadDelete(&thread_record_t);
}

bool func_record_start(){
    if (OS_ThreadIsValid(&thread_record_t))
    {
        #if 0 
        // 这样删除线程后，线程里面的资源没有释放，会有问题
        OS_Status  status =   OS_ThreadDelete(&thread_record_t);
        printf("OS_ThreadDelete status = %d \n", status );
        #endif
        func_record_stop();
    }
     OS_Status  status = OS_ThreadCreate(&thread_record_t , 
                                            "task_record",
                                            task_record_callback,
                                            NULL,
                                            OS_PRIORITY_NORMAL,
                                            1024 * 3);
    if (status != OS_OK)
    {
            printf("task record create error \n");
            return false ;
    }
    printf("task record create success \n");
    return true ;                                       
}

bool func_record_stop(){
    flag_recording = false ;
    while (true)
    {
            if (OS_ThreadIsValid( &thread_record_t))
            {
                    OS_MSleep(10);
            }else{
                    break;
            }
    }
    printf("func record stop \n");
}

void func_mock_record_test(){
    f_unlink( AUDIO_PATH_TEST );
    func_record_start();
    OS_MSleep(SAVE_RECORD_DATA_DURATION_MS);
    func_record_stop();

#if 0 
    f_unlink( AUDIO_PATH_TEST );
    func_record_start();
    OS_MSleep(SAVE_RECORD_DATA_DURATION_MS);
    func_record_stop();
#endif 
}